# coding:utf-8
"""
description:Security页面
"""
import random
import time

from appium.webdriver.common import mobileby

from common.Log import LOG
from config.GlobalParameter import TEST_Element_YAML
from common.Get_Yaml import get_yaml
from pages.Public_elements import public_elements
from common.Gesture_Mainpulation import gesture_mainpulation
import os

testElements = get_yaml(os.path.join(TEST_Element_YAML, "Security.yaml"))


class Security_page(public_elements):
    by = mobileby.MobileBy()

    SecurityHomeMode_loc = (by.ID, testElements.get_elementInfo(0))  # 点击Home mode按钮
    SecurityAwayMode_loc = (by.ID, testElements.get_elementInfo(1))  # 点击Away mode按钮
    SecurityDisable_loc = (by.ID, testElements.get_elementInfo(2))  # 点击Disable 按钮
    SecurityHistoryToday_loc = (by.ID, testElements.get_elementInfo(3))  # 点击Today按钮
    SecurityHistorySelectDay_loc = (by.ID, testElements.get_elementInfo(4))  # 点击SelectDay按钮
    SecurityHistorySort_loc = (by.ID, testElements.get_elementInfo(5))  # 点击Sort by按钮

    def click_SecurityHomeMode(self):
        """点击Home mode按钮"""
        if self.assert_MessageLogDevice():  # 需要等待security加载完成才能点击
            self.find_element(*self.SecurityHomeMode_loc).click()

    def click_SecurityAwayMode(self):
        """点击Away mode按钮"""
        if self.assert_MessageLogDevice():
            self.find_element(*self.SecurityAwayMode_loc).click()

    def click_SecurityDisable(self):
        """点击Disable 按钮"""
        if self.assert_MessageLogDevice():
            self.find_element(*self.SecurityDisable_loc).click()

    def click_SecurityHistoryToday(self):
        """点击Today按钮"""
        self.find_element(*self.SecurityHistoryToday_loc).click()

    def click_SecurityHistorySelectDay(self):
        """点击SelectDay按钮"""
        self.find_element(*self.SecurityHistorySelectDay_loc).click()

    def click_SecurityHistorySort(self):
        """点击Sort by按钮"""
        self.find_element(*self.SecurityHistorySort_loc).click()

    def func_SwitchMode(self, checktext):
        """
        切换mode，需要等待security log出现
        :param checktext:
        :return:
        """
        num = random.randint(1, 3)
        if num == 1:
            LOG.info("切换home mode。。。")
            self.click_SecurityHomeMode()
            return self.find_toast(checktext[0])
        elif num == 2:
            LOG.info("切换Away Mode。。。")
            self.click_SecurityAwayMode()
            return self.find_toast(checktext[1])
        else:
            self.click_SecurityDisable()
            return self.find_toast(checktext[2])

    CheckedTextView_loc = (by.CLASS_NAME, testElements.get_elementInfo(6))  # 点击日期按钮
    SecurityHistoryDelete_loc = (by.ID, testElements.get_elementInfo(7))  # 点击Security History Delete按钮
    HistorySelectAll_loc = (by.ID, testElements.get_elementInfo(16))  # 点击删除页面的select all
    HistoryCancel_loc = (by.ID, testElements.get_elementInfo(17))  # 取消删除，退出删除页面
    MessageLogDevice_loc = (by.ID, testElements.get_elementInfo(8))  # Device name
    MessageLogDeviceRoom_loc = (by.ID, testElements.get_elementInfo(9))  # 获取device 的floor 和room
    MessageLogDeviceDate_loc = (by.ID, testElements.get_elementInfo(19))  # 获取history的device date
    cbMessageLogDelete_loc = (by.ID, testElements.get_elementInfo(20))  # 删除页面的log数据单选框

    def get_CheckedTextView(self):
        """点击日期按钮,日期不固定"""
        return self.find_elements(*self.CheckedTextView_loc)

    def func_DelNull(self, checks):
        """
        点击日期按钮,当选择日期下没有数据，点击delete按钮
        :param checks: 提示框文案
        :return:
        """
        for index, row in enumerate(self.get_CheckedTextView()):
            if int(row.text) <= time.localtime(time.time()).tm_mday:
                row.click()  # 点击日期
                if self.assert_MessageLogDevice() == False:
                    self.click_SecurityHistoryDelete()
                    return super().find_toast(checks)

    def click_SecurityHistoryDelete(self):
        """点击Security History Delete按钮"""
        self.find_element(*self.SecurityHistoryDelete_loc).click()

    def click_HistorySelectAll(self):
        """点击删除页面的select all"""
        self.find_element(*self.HistorySelectAll_loc).click()

    def click_HistoryCancel(self):
        """取消删除，退出删除页面"""
        self.find_element(*self.HistoryCancel_loc).click()

    def get_MessageLogDevice(self):
        """点击Device name"""
        return self.find_elements(*self.MessageLogDevice_loc)

    def assert_MessageLogDevice(self):
        """点击Device name"""
        return self.assertVisible(*self.MessageLogDevice_loc)

    def get_MessageLogDeviceRoom(self):
        """获取device 的floor 和room"""
        return self.find_elements(*self.MessageLogDeviceRoom_loc)

    def get_MessageLogDeviceDate(self):
        """获取history的device date"""
        return self.find_elements(*self.MessageLogDeviceDate_loc)

    def get_cbMessageLogDelete(self):
        """删除页面的log数据单选框"""
        return self.find_elements(*self.cbMessageLogDelete_loc)

    def func_delHistorySelectAll(self):
        """
        删除全部log
        :return:MessageDeviceRoom不存在返回false
        """
        # for index, row in enumerate(self.get_CheckedTextView()):      #此段注释因为出现bug表B299，无法正确执行
        #     if int(row.text) <= time.localtime(time.time()).tm_mday:
        #         row.click()  # 点击日期
        #         if len(self.get_MessageLogDevice()) > 0:  # 判断日期下有数据则跳出循环
        #             LOG.info("Security：删除history log ，选择date是>>>%s"%row.text)
        #             break
        if self.assert_MessageLogDevice():  # 判断日期下有数据则跳出循环
            self.click_SecurityHistoryDelete()
            self.click_HistorySelectAll()
            self.click_SecurityHistoryDelete()
            try:
                super().click_btnDeletePopupDelete()
            except:
                LOG.info("security出现假数据，没有出现delete pop的确认按钮")
        else:
            LOG.info("security没有log 数据，点击按删除按钮无法跳转删除页面。。。")

    def func_delHistoryOther(self, indexs):
        """
        删除个别log
        :return:指定device date不存在返回false
        """
        # for index, row in enumerate(self.get_CheckedTextView()):      #此段注释因为出现bug表B299，无法正确执行
        #     if int(row.text) <= time.localtime(time.time()).tm_mday:
        #         row.click()  # 点击日期
        #         if len(self.get_MessageLogDevice()) > 0:  # 判断日期下有数据则跳出循环
        #             LOG.info("Security：删除history log ，选择date是>>>%s"%row.text)
        #             break
        if self.assert_MessageLogDevice():  # 判断日期下有数据则跳出循环
            self.click_SecurityHistoryDelete()
            self.get_cbMessageLogDelete()[indexs].click()
            delDev = self.get_MessageLogDeviceDate()[indexs].text
            self.click_SecurityHistoryDelete()
            try:
                super().click_btnDeletePopupDelete()
            except:
                LOG.info("security出现假数据，没有出现delete pop的确认按钮")
            """全部删除成功后页面显示为空，返回为false"""
            return self.find_toast(delDev)
        else:
            LOG.info("security没有log 数据，点击按删除按钮无法跳转删除页面。。。")

    """floor和room所有控件，默认选中状态。"""
    RoomMgmtRoomName_loc = (by.ID, testElements.get_elementInfo(10))
    design_bottom_sheet_loc = (by.ID, testElements.get_elementInfo(11))  # 点击定sort by框框外面表示确认
    SortByDevice_loc = (by.XPATH, testElements.get_elementInfo(21))  # sort by里面的device 集合

    def click_RoomMgmtRoomName(self):
        """floor和room所有控件，默认选中状态。"""
        self.find_element(*self.RoomMgmtRoomName_loc).click()

    def swipe_design_sheet(self, updown="up", cycle=1):
        """滑动security首页和setting mode时的弹框"""
        if updown == "up":
            for i in range(cycle):
                gesture_mainpulation().swipe_up(self.driver, self.find_element(*self.design_bottom_sheet_loc))
        else:
            for i in range(cycle):
                gesture_mainpulation().swipe_down(self.driver, self.find_element(*self.design_bottom_sheet_loc))

    def click_design_sheet_outside(self):
        """点击定sort by框框外面表示确认"""
        xy = gesture_mainpulation().centreXAndY(self.find_element(*self.design_bottom_sheet_loc))
        self.driver.tap([(xy[0], xy[5] - 200)], 500)

    def get_SortByDevice(self):
        """sort by里面的device 集合"""
        return self.find_elements(*self.SortByDevice_loc)

    def func_SortBySmoke(self):
        """
        只留smoke sensor进行筛查,缺少room and floor筛选
        :return: 筛选smoke没有数据，返回false
        """
        self.click_SecurityHistorySort()
        for index, row in enumerate(self.get_SortByDevice()):
            if index == 3:  # 当循环到第四个smoke sensor时，退出for循环不点击
                break
            row.click()
        self.click_design_sheet_outside()
        return super().assertVisible(self.MessageLogDevice_loc)

    SecuritySettingsHome_loc = (by.ID, testElements.get_elementInfo(12))  # 点击Home Mode一行
    SecuritySettingsAway_loc = (by.ID, testElements.get_elementInfo(13))  # 点击away Mode一行
    """点击home mode settings 页面的alarm condition devices一行"""
    SettingsHomeDevices_loc = (by.ID, testElements.get_elementInfo(14))
    """点击away mode settings 页面的alarm condition devices一行的数量"""
    SettingsAwayDevices_loc = (by.ID, testElements.get_elementInfo(25))
    SecurityFilterSelectAll_loc = (by.ID, testElements.get_elementInfo(15))  # 点击select all
    """security和删除history页面的settings 按钮"""
    btnSecuritySettings_loc = (by.ID, testElements.get_elementInfo(18))
    """security设置away和home页面的弹框device room"""
    DeviceFloorRoom_loc = (by.ID, testElements.get_elementInfo(22))
    """security设置away和home页面的弹框device 单选框"""
    cbSecurityDevice_loc = (by.ID, testElements.get_elementInfo(23))

    def click_SecuritySettingsHome(self):
        """点击Home Mode一行"""
        self.find_element(*self.SecuritySettingsHome_loc).click()

    def click_SecuritySettingsAway(self):
        """点击away Mode一行"""
        self.find_element(*self.SecuritySettingsAway_loc).click()

    def click_SettingsHomeDevices(self):
        """点击home mode settings 页面的alarm condition devices一行"""
        self.find_element(*self.SettingsHomeDevices_loc).click()

    def get_SettingsHomeDevices(self):
        """获取home mode settings 页面的alarm condition devices一行的数量"""
        return self.find_element(*self.SettingsHomeDevices_loc).text

    def click_SettingsAwayDevices(self):
        """点击away mode settings 页面的alarm condition devices一行"""
        self.find_element(*self.SettingsAwayDevices_loc).click()

    def get_SettingsAwayDevices(self):
        """获取away mode settings 页面的alarm condition devices一行的数量"""
        return self.find_element(*self.SettingsAwayDevices_loc).text

    def click_SecurityFilterSelectAll(self):
        """away和home mode settings 页面点击select all"""
        self.find_element(*self.SecurityFilterSelectAll_loc).click()

    def click_btnSecuritySettings(self):
        """security和删除history页面的settings 按钮"""
        self.find_element(*self.btnSecuritySettings_loc).click()

    def get_DeviceFloorRoom(self):
        """security设置away和home页面的弹框device room"""
        return self.find_elements(*self.DeviceFloorRoom_loc)

    def get_cbSecurityDevice(self):
        """security设置away和home页面的弹框device 单选框"""
        return self.find_elements(*self.cbSecurityDevice_loc)

    def func_SettingsAway(self):
        """
        设置away mode，全选所有device
        :return:
        """
        self.click_btnSecuritySettings()
        self.click_SecuritySettingsAway()
        self.click_SettingsAwayDevices()
        self.swipe_design_sheet("up", 2)
        devnum = len(self.get_DeviceFloorRoom())
        self.click_SecurityFilterSelectAll()
        self.swipe_design_sheet("down")  # 滑倒底部后自动保存
        print(int(self.get_SettingsAwayDevices()) == devnum,int(self.get_SettingsAwayDevices()),devnum)
        return int(self.get_SettingsAwayDevices()) == devnum

    def func_SettingsHome(self):
        """
        设置home mode，随机选中smoke、door/window、motion and button
        :return:
        """
        self.click_btnSecuritySettings()
        self.click_SecuritySettingsHome()
        self.click_SettingsHomeDevices()
        self.swipe_design_sheet("up", 2)
        for index, row in enumerate(self.get_cbSecurityDevice()):  # 取消之前选中的device
            print(row.get_attribute("checked"))
            if row.get_attribute("checked") == "true":
                row.click()
        random.choice(self.get_cbSecurityDevice()).click()  # 重新随机选择一个
        self.swipe_design_sheet("down")  # 滑倒底部后自动保存
        print(int(self.get_SettingsHomeDevices()))
        return int(self.get_SettingsHomeDevices()) == 1